package fpt.edu.vn.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.LocationDao;
import fpt.edu.vn.model.Districts;
import fpt.edu.vn.model.Locations;
import fpt.edu.vn.model.Locationtypes;
import fpt.edu.vn.model.Provinces;

/* 
 * AdminLocationDoAction.java 
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class AdminLocationDoAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private int provinceId;

	private String provinceName;

	private String districtName;

	private int locationId;

	private String locationName;

	private String description;

	private int locationTypeId;

	private String latitude;

	private String longitude;

	private int districtId;
	// add location
	private int city;
	// add city
	private int city3;
	// add district
	private int city1;
	// load data view
	private int city2;
	private String Username;
	private InputStream inputStream;
	private List<Provinces> lstProvince;
	private List<Locationtypes> lstLocationtypes;

	private LocationDao locationdao = new LocationDao();

	// For SessionAware
	Map<String, Object> session;

	public String addCity() {
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userRoleIdss")) {
			int isAdmin = (Integer) session.get("userRoleIdss");
			if (isAdmin == 1) {
				Provinces province = new Provinces();
				if (!"".equals(provinceName) && !"".equals(latitude)
						&& !"".equals(longitude)) {
					List<Provinces> lstprovinces = locationdao.provinceexist(
							provinceName, longitude, latitude);
					if (lstprovinces.size() < 1) {
						province.setProvinceName(decodeURIComponent(provinceName));
						province.setLatitude(latitude);
						province.setLongitude(longitude);
						province = locationdao.add(province);
					} else {
						inputStream = toUTF8InputStream("Địa điểm đã tồn tại!");
					}
				}
				if (province.getProvinceId() != 0) {
					inputStream = toUTF8InputStream("Add "
							+ province.getProvinceName().toString()
							+ " thành công!");
				}
				return SUCCESS;
			}
		}
		return ERROR;
	}

	public String addDistrict() {
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userRoleIdss")) {
			int isAdmin = (Integer) session.get("userRoleIdss");
			if (isAdmin == 1) {
				Districts district = new Districts();
				if (!"".equals(districtName) && !"".equals(latitude)
						&& !"".equals(longitude)) {
					List<Districts> lstdistrict = locationdao.districtexist(
							districtName, longitude, latitude);
					if (lstdistrict.size() < 1) {
						district.setDistrictName(decodeURIComponent(districtName));
						district.setProvinceId(provinceId);
						district.setLatitude(latitude);
						district.setLongitude(longitude);
						district = locationdao.add(district);
					} else {
						inputStream = toUTF8InputStream("Địa điểm đã tồn tại!");
					}
				}
				if (district.getDistrictId() != 0) {
					inputStream = toUTF8InputStream("Add "
							+ district.getDistrictName().toString()
							+ " thành công!");
				}
				return SUCCESS;
			}
		}
		return ERROR;
	}

	// list location

	public String listLocation() {
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userRoleIdss")) {
			int isAdmin = (Integer) session.get("userRoleIdss");
			if (isAdmin == 1) {
				
				List<Locations> lstLocation = new ArrayList<Locations>();

				lstLocation = locationdao.lstlocationload(districtId,
						locationTypeId);
				StringBuilder stblocation = new StringBuilder();
				for (int i = 0; i < lstLocation.size(); i++) {
					stblocation.append(lstLocation.get(i).getLocationId());
					stblocation.append("+");
					stblocation.append(lstLocation.get(i).getLocationName());
					stblocation.append("+");
					stblocation.append(lstLocation.get(i).getLatitude());
					stblocation.append(",");
					stblocation.append(lstLocation.get(i).getLongitude());
					stblocation.append("|");
				}
				inputStream = toUTF8InputStream(stblocation.toString());
				
				return SUCCESS;

			}
		}
		return ERROR;
	}
	//delete location
	public String deletelocation() {
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userRoleIdss")) {
			int isAdmin = (Integer) session.get("userRoleIdss");
			if (isAdmin == 1) {
				String namedelete = locationdao.lstlocationdelete(locationId).get(0).getLocationName();
				if(locationdao.deletedLocation(locationId))
				{
					List<Locations> lstLocation = new ArrayList<Locations>();

					lstLocation = locationdao.lstlocationload(districtId,
							locationTypeId);
					StringBuilder stblocation = new StringBuilder();
					for (int i = 0; i < lstLocation.size(); i++) {
						stblocation.append(lstLocation.get(i).getLocationId());
						stblocation.append("+");
						stblocation.append(lstLocation.get(i).getLocationName());
						stblocation.append("+");
						stblocation.append(lstLocation.get(i).getLatitude());
						stblocation.append(",");
						stblocation.append(lstLocation.get(i).getLongitude());
						stblocation.append("|");
					}stblocation.append(namedelete);
					inputStream = toUTF8InputStream(stblocation.toString());
				}
				return SUCCESS;

			}
		}
		return ERROR;
	}
	// end list location
	public String execute() {
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userRoleIdss")) {
			int isAdmin = (Integer) session.get("userRoleIdss");
			if (isAdmin == 1) {
				Locations location = new Locations();
				if (!"".equals(locationName) && !"".equals(latitude)
						&& !"".equals(longitude)) {
					List<Locations> locationtemp = locationdao.locationexist(
							locationName, longitude, latitude, description);

					if (locationtemp.size() < 1) {
						location.setLocationName(decodeURIComponent(locationName));
						location.setDistrictId(districtId);
						location.setDescription(decodeURIComponent(description));
						location.setLatitude(latitude);
						location.setLongitude(longitude);
						location.setLocationTypeId(locationTypeId);
						location = locationdao.add(location);
					} else {
						inputStream = toUTF8InputStream("Địa điểm đã tồn tại!");
					}
				}
				if (location.getLocationId() != 0) {
					inputStream = toUTF8InputStream("Add "
							+ location.getLocationName().toString()
							+ " thành công!");
				}
				return SUCCESS;

			}
		}
		return ERROR;

	}

	public static InputStream toUTF8InputStream(String str) {
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// UTF-8 should always be supported
			throw new AssertionError();
		}
		return is;
	}

	public Date getSysdate() {
		Date date = new Date();
		return date;
	}

	public String getStrDate() {
		String curdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		return curdate;
	}

	public static String decodeURIComponent(String encodedURI) {
		char actualChar;

		StringBuffer buffer = new StringBuffer();

		int bytePattern, sumb = 0;

		for (int i = 0, more = -1; i < encodedURI.length(); i++) {
			actualChar = encodedURI.charAt(i);

			switch (actualChar) {
			case '%': {
				actualChar = encodedURI.charAt(++i);
				int hb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				actualChar = encodedURI.charAt(++i);
				int lb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				bytePattern = (hb << 4) | lb;
				break;
			}
			case '+': {
				bytePattern = ' ';
				break;
			}
			default: {
				bytePattern = actualChar;
			}
			}

			if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
				sumb = (sumb << 6) | (bytePattern & 0x3f);
				if (--more == 0)
					buffer.append((char) sumb);
			} else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
				buffer.append((char) bytePattern);
			} else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
				sumb = bytePattern & 0x1f;
				more = 1;
			} else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
				sumb = bytePattern & 0x0f;
				more = 2;
			} else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
				sumb = bytePattern & 0x07;
				more = 3;
			} else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
				sumb = bytePattern & 0x03;
				more = 4;
			} else { // 1111110x
				sumb = bytePattern & 0x01;
				more = 5;
			}
		}
		return buffer.toString();
	}

	public String getDistrictName() {
		return districtName;
	}

	public void setDistrictName(String districtName) {
		this.districtName = districtName;
	}

	public int getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(int provinceId) {
		this.provinceId = provinceId;
	}

	public String getProvinceName() {
		return provinceName;
	}

	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}

	public String getUsername() {
		return Username;
	}

	public void setUsername(String username) {
		Username = username;
	}

	public List<Locationtypes> getLstLocationtypes() {
		return lstLocationtypes;
	}

	public void setLstLocationtypes(List<Locationtypes> lstLocationtypes) {
		this.lstLocationtypes = lstLocationtypes;
	}

	public List<Provinces> getLstProvince() {
		return lstProvince;
	}

	public void setLstProvince(List<Provinces> lstProvince) {
		this.lstProvince = lstProvince;
	}

	public int getLocationId() {
		return locationId;
	}

	public void setLocationId(int locationId) {
		this.locationId = locationId;
	}

	public String getLocationName() {
		return locationName;
	}

	public void setLocationName(String locationName) {
		this.locationName = locationName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public int getLocationTypeId() {
		return locationTypeId;
	}

	public void setLocationTypeId(int locationTypeId) {
		this.locationTypeId = locationTypeId;
	}

	public String getLatitude() {
		return latitude;
	}

	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public int getDistrictId() {
		return districtId;
	}

	public void setDistrictId(int districtId) {
		this.districtId = districtId;
	}

	public int getCity() {
		return city;
	}

	public void setCity(int city) {
		this.city = city;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

}
